<template>
  <div>
    <div style="padding-top: 50px">
      <h1>拼图验证码登录 Demo</h1>
      <table style="margin: auto;">
        <tr>
          <td>登录名：</td>
          <td><input type="text" v-model="username"></td>
        </tr>
        <tr>
          <td>密码：</td>
          <td><input type="password" v-model="password"></td>
        </tr>
      </table>
      <div style="padding: 5px"><input type="button" value="登录" @click="onClickLogin"></div>
    </div>
    <transition name="fade">
      <jigsaw-captcha
        ref="captcha"
        v-if="show"
        :show="show"
        :router="router"
        :register="registerCaptcha"
        :login="loginCaptcha"
        @close="onCloseCaptcha"
      ></jigsaw-captcha>
    </transition>
  </div>
</template>

<script>
import JigsawCaptcha from '@/components/CaptchaJigsaw'
import {check, register} from '@/api/jigsawCaptcha'

export default {
  name: 'Login',
  components: {JigsawCaptcha},

  data () {
    return {
      username: '',
      password: '',
      show: false,
      router: '/home'
    }
  },

  methods: {
    /**
     * 点击登录按钮
     */
    onClickLogin () {
      this.show = true
    },

    /**
     * 注册验证码
     */
    registerCaptcha () {
      return new Promise((resolve, reject) => {
        register().then(resp => {
          resolve(resp.data)
        }).catch(err => {
          reject(err)
        })
      })
    },

    /**
     * 拼图校验与登录
     */
    loginCaptcha (token, sliceX) {
      return new Promise((resolve, reject) => {
        let form = {
          username: this.username,
          password: this.password,
          token: token,
          sliceX: sliceX
        }
        check(form).then(resp => {
          resolve(resp.data)
        }, err => {
          reject(err)
        })
      })
    },

    /**
     * 关闭弹出验证码
     */
    onCloseCaptcha () {
      this.show = false
    }
  }
}
</script>

<style scoped>
table tr td {
  padding: 5px;
}

table tr td:first-child {
  text-align: right;
}

table tr td:last-child {
  text-align: left;
}

.fade-enter-active, .fade-leave-active {
  transition: opacity .4s;
}

.fade-enter, .fade-leave-to {
  opacity: 0;
}
</style>
